package openapi

import (
	"encoding/json"
	"fmt"

	"github.com/getkin/kin-openapi/openapi3"
)

// 将参数按风格转换为可用于参数设置等的字符串,用在query、path、header、cookie等参数的设置
func EncodingParToString(def *openapi3.Schema, style string, value interface{}) string {
	if style == "" {
		if value == nil {
			return ""
		}
		if def == nil {
			return value.(string)
		}

		switch def.Type {
		// case "object":
		// case "array":
		default:
			//输入只有string和object、array三种
			return value.(string)
		}
	} else {
		switch style {
		case "jsonString": //扩展类型，将object或者array生成json串行后的string
			bts, _ := json.Marshal(value)
			return string(bts)
		}
		return fmt.Sprintf("%v", value)
	}
	return ""
}

// 根据输入进行请求的创建
func (c *CallingSession) generateReqBySchema(handledMark *map[string]interface{}, properties openapi3.Schemas,
	encoding map[string]*openapi3.Encoding, mSel *OperationSelection,
	parameters openapi3.Parameters, inputs map[string]interface{}, fn DefHandler) (hasChange bool, result map[string]interface{}, err error) {
	var request = make(map[string]interface{})
	for name, def := range properties {
		var result interface{}
		_, result, err = GetValue(
			name,
			"body",
			mSel.RequestBody.Default,
			c, handledMark)
		if err == NullValue {
			continue
		} else if err != nil {
			return hasChange, request, err
		} else {
			var hasChangeSingle bool
			hasChangeSingle, result, _ = fn.TransformValueVersa(def.Value, result)
			hasChange = hasChange || hasChangeSingle
			request[name] = result
		}
	}
	return hasChange, request, err
}
